package com.barbarossa.activity.data;

import java.util.ArrayList;

import com.barbarossa.vod.datatype.VodHistoryRecord;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.ext.DatabaseClosedException;
import com.db4o.ext.DatabaseReadOnlyException;

public class VodDataManager {
	// accessDb4o
	private static final String DB4OFILENAME = "vod.db";
	private static VodDataManager instance = null;
	private static String DB4OFILEPATH = "/sdcard";

	private VodDataManager() {
		super();
		// TODO Auto-generated constructor stub
	}

	synchronized public static VodDataManager getInstance(String path) {

		if (null == instance) {
			instance = new VodDataManager();
			if (null != path)
				instance.DB4OFILEPATH = path;
		}

		return instance;
	}

	public boolean addVodHistoryRecord(VodHistoryRecord obj) {

		ObjectContainer db = Db4oEmbedded.openFile(
				Db4oEmbedded.newConfiguration(), DB4OFILEPATH + "/"
						+ DB4OFILENAME);
		try {
			db.store(obj);
		} catch (DatabaseClosedException e) {
			e.printStackTrace();
			return false;
		} catch (DatabaseReadOnlyException e) {
			e.printStackTrace();
			return false;
		} finally {
			db.close();
		}

		return true;
	}
	
//	public boolean restoreVodHistoryRecords(ArrayList<VodHistoryRecord>) {
//		
//	}
	
	public ArrayList<VodHistoryRecord> getVodHistoryRecords() {

		ObjectContainer db = Db4oEmbedded.openFile(
				Db4oEmbedded.newConfiguration(), DB4OFILEPATH + "/"
						+ DB4OFILENAME);
		ArrayList<VodHistoryRecord> ret = new ArrayList<VodHistoryRecord>();
		try {
			ObjectSet<VodHistoryRecord> result = db.queryByExample(VodHistoryRecord.class);
			
		    while(result.hasNext()) {
		    	ret.add(0, result.next());
		    }
		} catch (DatabaseClosedException e) {
			e.printStackTrace();
		} catch (DatabaseReadOnlyException e) {
			e.printStackTrace();
		} finally {
			db.close();
		}

		return ret;
	}
	
	public boolean clearAll() {

		ObjectContainer db = Db4oEmbedded.openFile(
				Db4oEmbedded.newConfiguration(), DB4OFILEPATH + "/"
						+ DB4OFILENAME);
		try {
			ObjectSet objects = db.queryByExample(null);
		    for (Object object : objects) {
		        db.delete(object);
		    }
		} catch (DatabaseClosedException e) {
			e.printStackTrace();
			return false;
		} catch (DatabaseReadOnlyException e) {
			e.printStackTrace();
			return false;
		} finally {
			db.close();
		}

		return true;
	}	
	
}
